/*
 * @Description:
 * @Version: 2.0
 * @Autor: Seven
 * @Date: 2025-04-23 13:24:45
 * @LastEditors: Seven
 * @LastEditTime: 2025-05-06 15:26:00
 */
export class WebSocketService {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.maxRetries = 3; // 新增最大重试次数
    this.listeners = new Map();
    this.reconnectInterval = 5000; // 5秒重连
  }

  connect() {
    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log('WebSocket 连接成功');
      this.retries = 0;
    };

    this.socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        this.listeners.forEach(callback => callback(data));
      } catch (error) {
        console.error('数据解析失败:', error);
      }
    };

    this.socket.onclose = () => {
      console.log('WebSocket 断开，尝试重连...');
      if (this.retries < this.maxRetries) {
        this.retries++;
        setTimeout(() => this.connect(), this.reconnectInterval);
      }
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket 错误:', error);
    };
  }

  addListener(key, callback) {
    this.listeners.set(key, callback);
  }

  removeListener(key) {
    this.listeners.delete(key);
  }

  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.listeners.clear();
    }
  }
}

